package com.itmiaojie.controller;

import com.itmiaojie.handle.exception.SystemException;
import com.itmiaojie.pojo.*;
import com.itmiaojie.pojo.vo.AdminUserInfoVo;
import com.itmiaojie.pojo.vo.RoutersVo;
import com.itmiaojie.service.LoginService;
import com.itmiaojie.service.MenuService;
import com.itmiaojie.service.RoleService;
import com.itmiaojie.service.UserService;
import com.itmiaojie.utils.BeanCopyUtils;
import com.itmiaojie.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController

public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserService userService;
    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user){
        System.out.println(user);
        if (StringUtils.isEmpty(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        return loginService.login(user);
    }

    @GetMapping("/getInfo")
    public ResponseResult getInfo(){
        //获取用户id
        Long userId = SecurityUtils.getUserId();
        //根据用户id查询权限信息
        List<String> permList = menuService.selectUserPassionsById(userId);
        //根据id查询角色信息
        List<String> roleList = roleService.selectUserRoleById(userId);
        //查询用户信息
        User user = userService.getById(userId);
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class);
        AdminUserInfoVo adminUserInfoVo = new AdminUserInfoVo(permList, roleList, userInfoVo);
        return ResponseResult.okResult(adminUserInfoVo);
    }

    @GetMapping("/getRouters")
    public ResponseResult getRouters(){
        Long userId = SecurityUtils.getUserId();
        //查询menu 结果是tree的形式
        List<Menu> menus = menuService.selectRouterMenuTreeByUserId(userId);
        //封装数据返回
        return ResponseResult.okResult(new RoutersVo(menus));
    }
    @PostMapping("/user/logout")
    public ResponseResult logout(){
        return loginService.logout();
    }

}
